# 作者: 家里蹲 吴越洋
# 2023年03月07日15时53分37秒
from socket import *
import select

#初始化套接字
server_socket=socket(AF_INET,SOCK_STREAM)
#重用对应地址和端口
server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
#绑定套接字
server_socket.bind(('',4000))
#设置为监听
server_socket.listen(10)
client_socket, client_addr=server_socket.accept()
print(f'{client_addr}连上了')
epoll=select.epoll()
# epoll小兵监视标准输入
epoll.register(sys.stdin.fileno(),select.EPOLLIN)
# epoll小兵监视client_socket
epoll.register(client_socket.fileno(),select.EPOLLIN)

while True:
    # -1永久等待，轮询注册的事件集合，返回值为[(文件句柄，对应的事件)，(...),....]
    events=epoll.poll(-1,2)
    for event in events:
        if event[0]==sys.stdin.fileno():
            data=input()
            client_socket.send(data.encode('utf8'))
        elif event[0]==client_socket.fileno():
            recv_data=client_socket.recv(1024)
            if recv_data:
                print('client:',recv_data.decode('utf8'))
            else:
                print('byebye')
                server_socket.close()
                client_socket.close()
                exit(0)
